package com.titaniume.sync;

import java.util.concurrent.TimeUnit;

/**
 * @ProjectName: juc
 * @Package: com.titaniume.sync
 * @ClassName: DeadLock
 * @Author: huangrenfei
 * @Description: 死锁演示
 * @Date: 2021/11/23 11:34
 * @Version: 1.0
 */
public class DeadLock {


    public static void main(String[] args) {

        Object a = new Object();
        Object b = new Object();


        new Thread(() ->{

            synchronized (a){
                System.out.println(Thread.currentThread().getName()+" 持有锁a，试图获取锁b");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (b){
                    System.out.println(Thread.currentThread().getName()+" 获得锁b");
                }
            }

        },"线程A").start();



        new Thread(() ->{

            synchronized (b){
                System.out.println(Thread.currentThread().getName()+" 持有锁b，试图获取锁a");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (a){
                    System.out.println(Thread.currentThread().getName()+" 获得锁a");
                }
            }

        },"线程B").start();

        //线程A和线程B休眠1秒 变成死锁
        //线程A 持有锁a，试图获取锁b
        //线程B 持有锁b，试图获取锁a

        //查看死锁
        //jps -l
        //jstack  进程ID
    }
}
